package webapi.storage.localdisk;

import org.springframework.core.io.FileSystemResource;
import webapi.storage.WriteOnlyDataChunk;

import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;


public class LocalDiskWriteOnlyDataChunk implements Closeable, WriteOnlyDataChunk {
    private final Path filePath;
    private final FileChannel outputFileChannel;

    /**
     * @throws IOException 文件无法创建, 请检查文件存储路径权限是否允许写入
     */
    public LocalDiskWriteOnlyDataChunk(Path filePath) throws IOException {
        this.filePath = filePath;
        outputFileChannel = FileChannel.open(filePath,
                StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING,
                StandardOpenOption.WRITE);
    }

    @Override
    public org.springframework.core.io.Resource getResource() {
        return new FileSystemResource(filePath);
    }

    /**
     * @throws IOException 文件读写错误
     */
    @Override
    public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
        return outputFileChannel.transferFrom(src, position, count);
    }

    /**
     * @throws IOException 磁盘IO错误导致文件无法关闭
     */
    @Override
    public void close() throws IOException {
        if (null != outputFileChannel) {
            outputFileChannel.close();
        }
    }
}
